package com.gmq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmq.common.BaseContext;
import com.gmq.common.R;
import com.gmq.dto.OrdersDto;
import com.gmq.entity.*;
import com.gmq.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("用户下单{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize) {
        log.info("查询订单{},{}", page, pageSize);
        Page<OrdersDto> ordersDtoPage = orderService.userPage(page, pageSize);
        return R.success(ordersDtoPage);
    }

    @GetMapping("/page")
    public R<Page<OrdersDto>> page(int page, int pageSize, Long number, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<Orders> page1 = new Page<>(page, pageSize);
        Page<OrdersDto> page2 = new Page<>();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number != null, Orders::getNumber, number);
        queryWrapper.ge(beginTime != null, Orders::getOrderTime, beginTime);
        queryWrapper.lt(endTime != null, Orders::getOrderTime, endTime);
        orderService.page(page1, queryWrapper);
        BeanUtils.copyProperties(page1, page2, "records");
        List<OrdersDto> list = new ArrayList<>();
        for (Orders record : page1.getRecords()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record, ordersDto);
            User userServiceById = userService.getById(record.getUserId());
            String name = userServiceById.getPhone();
            ordersDto.setUserName(name);
            list.add(ordersDto);
        }
        page2.setRecords(list);
        return R.success(page2);
    }

    @PutMapping
    public R<String> putOrder(@RequestBody Orders orders) {
        orderService.updateById(orders);
        return R.success("修改成功");
    }
}
